package com.dingup.mock.controller.reading;

import com.dingup.api.base.HttpResContent;
import com.dingup.mock.bean.exam.ExaminationInfo;
import com.dingup.mock.bean.reading.*;
import com.dingup.mock.dao.reading.TsReadingArticleDAO;
import com.dingup.mock.dao.reading.TsReadingQuestionDAO;
import com.dingup.mock.enums.ExamContentTypeEnum;
import com.dingup.mock.module.SExaminationQueueCache;
import com.dingup.mock.util.ConstUtil;
import com.dingup.mock.util.SysUtil;
import com.suyeer.basic.util.BHttpResUtil;
import com.suyeer.basic.util.BLogUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.dingup.api.base.BaseUtil.*;
import static com.dingup.mock.util.ConstUtil.RESPONSE_CODE_ERROR;
import static com.dingup.mock.util.ConstUtil.RESPONSE_CODE_SUCCESS;
import static com.dingup.util.GConstUtil.STRING_EMPTY;

/**
 * Created by yanggavin on 16/3/16.
 */
@Controller
@RequestMapping("/reading")
public class ReadingController {
    @Autowired
    private TsReadingArticleDAO tsReadingArticleDAO;
    @Autowired
    private TsReadingQuestionDAO tsReadingQuestionDAO;

    /**
     * 获取阅读文章
     *
     * @param subjectName 套题名称
     * @param articleNum  文章序号
     * @param response    response
     */
    @RequestMapping(value = "/get_article.do", method = RequestMethod.POST)
    public void getArticle(@RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM) Integer articleNum,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        HttpResContent<TsReadingArticle> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取文章信息");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            checkParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM, articleNum.toString());
            // do
            TsReadingArticle article = tsReadingArticleDAO.get(subjectName, articleNum);
            saveSuccessMsgAndData(hrc, article);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    @RequestMapping(value = "/get_article_num.do", method = RequestMethod.POST)
    private void getArticleNumBySubjectName(@RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                                            HttpServletRequest request,
                                            HttpServletResponse response) {
        HttpResContent<Integer> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取套题文章总数");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            // do
            Integer totalNum = tsReadingArticleDAO.getArticleTotalNum(subjectName);
            saveSuccessMsgAndData(hrc, totalNum);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 获取问题
     *
     * @param subjectName 套题名称
     * @param articleNum  文章序号
     * @param questionNum 问题序号
     * @param response    response
     */
    @RequestMapping(value = "/get_question.do", method = RequestMethod.POST)
    public void getQuestion(@RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                            @RequestParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM) Integer articleNum,
                            @RequestParam(ConstUtil.REQUEST_PARAMETER_QUESTION_NUM) Integer questionNum,
                            HttpServletRequest request,
                            HttpServletResponse response) {
        HttpResContent<TsReadingQuestion> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取题目信息");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            checkParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM, articleNum.toString());
            checkParam(ConstUtil.REQUEST_PARAMETER_QUESTION_NUM, questionNum.toString());
            // do
            TsReadingQuestion question = tsReadingQuestionDAO.getQuestion(subjectName, articleNum, questionNum);
            saveSuccessMsgAndData(hrc, question);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 获取问题列表
     *
     * @param subjectName 套题名称
     * @param articleNum  文章序号
     * @param response    response
     */
    @RequestMapping(value = "/get_questions.do", method = RequestMethod.POST)
    public void getQuestions(@RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                             @RequestParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM) Integer articleNum,
                             HttpServletRequest request,
                             HttpServletResponse response) {
        HttpResContent<List<TsReadingQuestion>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取题目列表信息");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            checkParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM, articleNum.toString());
            // do
            List<TsReadingQuestion> questionList = tsReadingQuestionDAO.getQuestions(subjectName, articleNum);
            saveSuccessMsgAndData(hrc, questionList);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 保存某一问题答案
     *
     * @param examinationId 考试ID
     * @param subjectName   套题名称
     * @param articleNum    文章序号
     * @param questionNum   问题序号
     * @param answer        答案:a,b
     * @param response      response
     */
    @RequestMapping(value = "/save_answer.do", method = RequestMethod.POST)
    public void saveAnswer(@RequestParam(ConstUtil.REQUEST_PARAMETER_EXAMINATION_ID) String examinationId,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME) String subjectName,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM) Integer articleNum,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_QUESTION_NUM) Integer questionNum,
                           @RequestParam(ConstUtil.REQUEST_PARAMETER_ANSWER) String answer,
                           HttpServletRequest request,
                           HttpServletResponse response) {
        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("答案保存");
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_SUBJECT_NAME, subjectName);
            checkParam(ConstUtil.REQUEST_PARAMETER_ARTICLE_NUM, articleNum.toString());
            checkParam(ConstUtil.REQUEST_PARAMETER_QUESTION_NUM, questionNum.toString());
            checkParam(ConstUtil.REQUEST_PARAMETER_EXAMINATION_ID, examinationId);
            // do.
            ExaminationInfo ei = SExaminationQueueCache.getInstance().getExaminationInfo(examinationId);
            ExamReadingInfo eri = ei.getExamReadingInfo();
            if (eri.getAnswerMap().get(articleNum).containsKey(questionNum)) {
                eri.getAnswerMap().get(articleNum).put(questionNum, answer);
                // log answer
                SysUtil.logExamRecordInfo(ei.getUserId(), examinationId, ExamContentTypeEnum.READING, articleNum, questionNum, answer);
            }
            ei.setExamReadingInfo(eri);
            //// 每次更新答案, 都更新记录的最后访问时间, 以延长缓存时间
            ei.setLastUpdateTime(new Date());
            ei.setCurAnswerProcess(ExamContentTypeEnum.READING, String.format("a%s-q%s", articleNum, questionNum));
            // 同步数据到MC
            SExaminationQueueCache.getInstance().syncDataToMC(examinationId, ei);
            // response.
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

    /**
     * 获取答题统计信息
     *
     * @param examinationId 考试ID
     * @param response      response
     */
    @RequestMapping(value = "/get_summary_info.do", method = RequestMethod.POST)
    public void getSummaryInfo(@RequestParam(ConstUtil.REQUEST_PARAMETER_EXAMINATION_ID) String examinationId,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        HttpResContent<List<ReadingSummaryInfo>> hrc = new HttpResContent<>(request, response);
        try {
            // check param valid
            checkParam(ConstUtil.REQUEST_PARAMETER_EXAMINATION_ID, examinationId);
            // do
            ExamReadingInfo eri = SExaminationQueueCache.getInstance().getExaminationInfo(examinationId).getExamReadingInfo();
            List<ReadingSummaryInfo> readingSummaryInfoList = new ArrayList<>();
            for (Map.Entry<Integer, Integer> entry : eri.getArticleMap().entrySet()) {
                ReadingSummaryInfo rsi = new ReadingSummaryInfo();
                rsi.setArticleNum(entry.getKey());
                TsReadingArticle tra = tsReadingArticleDAO.getById(entry.getValue());
                List<ReadingAnswerInfo> answerInfoList = new ArrayList<>();
                if (tra != null) {
                    List<TsReadingQuestion> questionList = tsReadingQuestionDAO.getQuestions(tra.getSubjectName(), entry.getKey());
                    for (Map.Entry<Integer, String> answer : eri.getAnswerMap().get(entry.getKey()).entrySet()) {
                        ReadingAnswerInfo rai = new ReadingAnswerInfo();
                        rai.setQuestionNum(answer.getKey());
                        rai.setStudentAnswer(answer.getValue());
                        for (TsReadingQuestion trq : questionList) {
                            if (trq.getQuestionNum().equals(answer.getKey())) {
                                if (trq.getQuestionXml() != null) {
                                    rai.setQuestionTitle(trq.getQuestionXml().getTitle());
                                    rai.setCorrectAnswer(StringUtils.join(trq.getQuestionXml().getAnswer(), ","));
                                } else {
                                    rai.setQuestionTitle(STRING_EMPTY);
                                    rai.setCorrectAnswer(STRING_EMPTY);
                                }
                                break;
                            }
                        }
                        answerInfoList.add(rai);
                    }
                }
                rsi.setAnswerInfoList(answerInfoList);
                readingSummaryInfoList.add(rsi);
            }
            hrc.fillData(RESPONSE_CODE_SUCCESS, "已获取答题统计信息", readingSummaryInfoList);
        } catch (Exception e) {
            BLogUtil.error(e);
            hrc.fillData(RESPONSE_CODE_ERROR, "获取答题统计信息失败", null);
        } finally {
            BHttpResUtil.writeResult(hrc);
        }
    }

}